# coding=utf-8

from . import admin
from flask import request, render_template, jsonify
from app import PAGE_NUM, page_code, util
from dbConnection.MysqlConn import Mysql
import math, time
import user_order
import sys
reload(sys)
sys.setdefaultencoding('utf8')


# 用户洗车记录表
@admin.route('/admin/user_wash_list.html')
@util.admin_login
def user_wash_list():
    md = user_order.get_store_list()
    jq = user_order.get_jq_list()
    return render_template('admin/wash/user_wash_list.html', md=md, jq=jq)


# 获取洗车列表数据
@admin.route('/admin/user_wash_list_post', methods=['post'])
@util.admin_login
def user_wash_list_post():
    parms = ['uid', 'day', 'mid', 'sid']
    maps = {}
    for d in parms:
        maps[d] = request.values.get(d)
    p = request.values.get('p', default='1')
    c_num = (int(p) - 1)*PAGE_NUM
    sql = "select w.uid, w.washTime, u.wxNickName, u.washNum, m.machineNum, s.storeName, w.plateNum FROM car_wash AS w LEFT " \
          "JOIN car_users AS u ON u.uid = w.uid LEFT JOIN store AS s ON s.storeId = w.storeId LEFT JOIN car_machine " \
          "AS m ON m.machineId = w.machineId WHERE 1=1"
    sql2 = "select count(w.uid) AS con FROM car_wash AS w LEFT JOIN car_users AS u ON u.uid = w.uid LEFT JOIN store " \
           "AS s ON s.storeId = w.storeId LEFT JOIN car_machine AS m ON m.machineId = w.machineId WHERE 1=1"
    if maps['uid']:
        sql += " and w.uid = '%s'" % maps['uid']
        sql2 += " and w.uid = '%s'" % maps['uid']
    if maps['day']:
        s_str = maps['day'] + ' 00:00:00'
        e_str = maps['day'] + ' 23:59:59'
        sql += " and w.washTime >= '%s' and w.washTime <= '%s'" % (s_str, e_str)
        sql2 += " and w.washTime >= '%s' and w.washTime <= '%s'" % (s_str, e_str)
    if maps['mid']:
        sql += " and w.machineId = '%s'" % maps['mid']
        sql2 += " and w.machineId = '%s'" % maps['mid']
    if maps['sid']:
        sql += " and w.storeId = '%s'" % maps['sid']
        sql2 += " and w.storeId = '%s'" % maps['sid']
    sql += " order by w.washTime desc limit %d, %d" % (c_num, PAGE_NUM)
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    cont = mysql.getOne(sql2, None)
    mysql.dispose()
    if res:
        for d in res:
            d['machineNum'] = '未知' if d['machineNum'] is None else d['machineNum']
    if cont:
        pages = math.ceil(cont['con'] / float(PAGE_NUM))
    else:
        pages = 0
    pages = int(pages)
    route_path = 'get_data'
    if pages > 0:
        html_str = page_code.page_code_html_post(int(p), route_path, pages)
    else:
        html_str = ''
    if res:
        for d in res:
            d['washTime'] = str(d['washTime'])
        data = {
            'status':1,
            'res':res,
            'page':html_str,
            'count':cont['con'],
            'p':p
        }
    else:
        data = {
            'status':2,
            'page':html_str
        }
    return jsonify(data)